<template>
  <!-- 新增外层容器适配父组件高度 -->
  <div class="ai-dialogue-wrapper">
    <!-- 消息列表区域 -->
    <div class="message-list" ref="messageList">
      <!-- 欢迎消息 -->
      <div class="welcome-message" v-if="messages.length === 0 && !deepseekLoading">
        <div class="welcome-icon">
          <el-icon :size="48" name="chat-round"></el-icon>
        </div>
        <h3>欢迎使用智能对话助手</h3>
        <p>我可以帮助你解答问题、提供信息和建议</p>
        <p>输入你的问题，按Enter发送消息</p>
      </div>

      <!-- 消息列表 -->
      <div
          class="message-item"
          v-for="msg in messages"
          :key="msg.id"
          :class="{ 'ai-message': msg.isAI, 'user-message': !msg.isAI }"
      >
        <div class="avatar" v-if="msg.isAI">
          <el-icon class="icon" name="chat-round"></el-icon>
        </div>
        <div class="message-bubble">
          <div class="content" v-if="msg.isAI" v-html="msg.html"></div>
          <div class="content" v-else>{{ msg.text }}</div>
          <div class="time">{{ formatTime(msg.timestamp) }}</div>
        </div>
        <div class="avatar" v-if="!msg.isAI">
          <el-icon class="icon" name="user"></el-icon>
        </div>
      </div>

      <!-- 加载状态 -->
      <div class="loading-indicator" v-if="deepseekLoading">
        <el-icon :size="20" class="loading-icon" name="loading"></el-icon>
        <span class="loading-text">AI正在思考...</span>
      </div>
    </div>

    <!-- 输入区域（固定在底部） -->
    <div class="input-area">
      <el-input
          v-model="message"
          placeholder="输入消息，按Enter发送，Shift+Enter换行..."
          :disabled="deepseekLoading"
          @keydown.enter.exact="sendMessage"
          @keydown.enter.shift="handleShiftEnter"
          type="textarea"
          :rows="3"
          clearable
          class="message-input"
      />
      <div class="button-group">
        <el-button
            type="primary"
            @click="sendMessage"
            :loading="deepseekLoading"
            class="send-btn"
            :disabled="!message.trim() || deepseekLoading"
        >
          <el-icon :size="18" name="send"></el-icon>
          发送
        </el-button>
        <el-button
            type="default"
            @click="updateConversation"
            :loading="deepseekLoading"
            :disabled="messages.length === 0 || deepseekLoading"
        >
          <el-icon :size="18" name="refresh"></el-icon>
          更新对话
        </el-button>
      </div>
    </div>

    <!-- 清空对话确认框 -->
    <el-dialog
        v-model="showClearDialog"
        title="确认清空"
        width="300px"
        :show-close="false"
    >
      <p>确定要清空当前对话记录吗？</p>
      <template #footer>
        <el-button @click="showClearDialog = false">取消</el-button>
        <el-button type="primary" @click="clearConversation">确认清空</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 脚本逻辑保持不变（与之前一致）
import { reactive, ref, watch, nextTick, onMounted } from 'vue'
import { useDeepseekService } from '@/api/Table/deepseekApi'
import { v4 as uuidv4 } from 'uuid'
import { marked } from 'marked';
import { sqlStore } from '@/store/sql/sql.js'
import {apiKeyStore} from "@/store/sql/ApiKey.js";
import {BaseResponse} from "@/api/Table/TableApi.js";

interface Message {
  id: string
  text: string
  html: string
  isAI: boolean
  timestamp: Date
}

const generateConvId = () => {
  return Math.random().toString(36).substring(2, 10);
}

const convId = ref(generateConvId())
const { deepseek, loading: deepseekLoading } = useDeepseekService()

const message = ref('')
const messageList = ref<HTMLElement | null>(null)
const messages = reactive<Message[]>([])
const showClearDialog = ref(false)

const params = reactive({
  convId: convId.value,
  get apiKey() {
    return apiKeyStore.apiKey
  },
  get model() {
    return apiKeyStore.model
  },
  query: "",
})

const formatTime = (date: Date) => {
  return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })
}

const handleShiftEnter = () => {
  message.value += '\n'
}

const sendMessage = async () => {
  const userInput = message.value.trim()
  if (!userInput || deepseekLoading.value) return
  const userMsg: Message = {
    id: uuidv4(),
    text: userInput,
    html: '',
    isAI: false,
    timestamp: new Date()
  }
  messages.push(userMsg)
  message.value = ""

  try {
    let query = ""
    if (sqlStore.sql2IsSend) query =sqlStore.sql2+"。"+ userInput+"。"
    if (sqlStore.sql1IsSend) query = query+"请你参考一下sql表回答我的问题，" +
        "如果我问的是有关生成增删改查等sql语句"+ sqlStore.sql1

    params.convId = convId.value
    params.query = query
    const res = await deepseek(params) as unknown as BaseResponse<string>
    const aiReply = <string>res.data.data|| "收到消息，但未获取到具体内容"
    messages.push({
      id: uuidv4(),
      text: aiReply,
      html:  marked.parse(aiReply, { async: false }),
      isAI: true,
      timestamp: new Date()
    })
  } catch (err: any) {
    let errorMsg = "发送失败，请稍后重试"
    console.log(err)
    if (err.message.includes('Network Error')) {
      errorMsg = "网络连接失败，请检查网络"
    } else if (err.response?.status === 401) {
      errorMsg = "API密钥无效，请检查配置"
    }

    messages.push({
      id: uuidv4(),
      text: errorMsg,
      html: errorMsg,
      isAI: true,
      timestamp: new Date()
    })
  }
}

const updateConversation = async () => {
  if (messages.length === 0 || deepseekLoading.value) return

  const lastUserMessage = messages.slice().reverse().find(msg => !msg.isAI)
  if (!lastUserMessage) return

  const lastAiMessageIndex = messages.findLastIndex(msg => msg.isAI)
  if (lastAiMessageIndex > -1) {
    messages.splice(lastAiMessageIndex, 1)
  }

  try {
    let query = lastUserMessage.text
    if (sqlStore.sql1IsSend) query += sqlStore.sql1
    if (sqlStore.sql2IsSend) query += sqlStore.sql2

    params.convId = convId.value
    params.query = query
    const res = await deepseek(params)
    const aiReply =<string>res || "收到消息，但未获取到具体内容"

    messages.push({
      id: uuidv4(),
      text: aiReply,
      html:  marked.parse(aiReply, { async: false }),
      isAI: true,
      timestamp: new Date()
    })
  } catch (err: any) {
    let errorMsg = "更新失败，请稍后重试"
    if (err.message.includes('Network Error')) {
      errorMsg = "网络连接失败，请检查网络"
    } else if (err.response?.status === 401) {
      errorMsg = "API密钥无效，请检查配置"
    }

    messages.push({
      id: uuidv4(),
      text: errorMsg,
      html: errorMsg,
      isAI: true,
      timestamp: new Date()
    })
  }
}

const clearConversation = () => {
  messages.length = 0
  convId.value = generateConvId()
  showClearDialog.value = false
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight
    }
  })
}

watch(messages, scrollToBottom, { deep: true })
onMounted(scrollToBottom)

watch(messages, () => {
  if (messages.length > 100) {
    messages.splice(0, messages.length - 100)
  }
})
</script>

<style scoped>
/* 关键：适配父组件的 flex 布局 */
.ai-dialogue-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%; /* 继承父组件高度 */
}

/* 消息列表区域 - 占满剩余空间并可滚动 */
.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f7f8fa;
  scroll-behavior: smooth;
}

/* 输入区域 - 固定在底部 */
.input-area {
  display: flex;
  gap: 12px;
  padding: 16px 0; /* 仅上下内边距，左右继承父组件 padding */
  border-top: 1px solid #f0f2f5;
  background-color: #fff;
  box-shadow: 0 -1px 4px rgba(0, 0, 0, 0.03);
  margin-top: auto; /* 关键：贴紧底部 */
  margin-bottom: 100px; /* 与底部保持 20px 距离 */
}

/* 其他原有样式保持不变 */
.welcome-message {
  text-align: center;
  padding: 40px 20px;
  color: #86909c;
  max-width: 500px;
  margin: 0 auto;
}

.welcome-icon {
  margin-bottom: 20px;
  color: #409eff;
  opacity: 0.8;
}

.message-item {
  display: flex;
  margin-bottom: 18px;
  max-width: 80%;
  animation: fadeIn 0.3s ease;
  align-items: flex-end;
}

.ai-message {
  align-self: flex-start;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
  align-self: flex-end;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  flex-shrink: 0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}

.ai-message .avatar {
  background-color: #f0f2f5;
  color: #409eff;
}

.user-message .avatar {
  margin-right: 0;
  margin-left: 10px;
  background-color: #409eff;
  color: white;
}

.message-bubble {
  position: relative;
  padding: 12px 16px;
  border-radius: 14px;
  word-break: break-word;
  line-height: 1.6;
  max-width: calc(100% - 46px);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.ai-message .message-bubble {
  background-color: white;
  border: 1px solid #f0f2f5;
  border-top-left-radius: 4px;
}

.user-message .message-bubble {
  background-color: #409eff;
  color: white;
  border-top-right-radius: 4px;
}

.time {
  font-size: 12px;
  margin-top: 4px;
  opacity: 0.7;
  text-align: right;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px 0;
  color: #606266;
  animation: pulse 1.5s infinite;
}

.message-input {
  flex: 1;
  min-width: 0; /* 防止被挤压 */
}

.button-group {
  display: flex;
  gap: 8px;
  align-items: flex-end;
}

/* 动画和滚动条样式保持不变 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.6; }
  100% { opacity: 1; }
}

.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}
</style>